package com.fileutils;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.widget.TextView;

import java.io.*;

/**
 * Created by Administrator on 2019/4/12.
 */

public class ImageFileUtil {
    /**
     * 相机和相册图片解析
     *
     * @param path
     * @param status true 相机  false  相册
     * @return
     */
    public static Bitmap analyzePic(Context activity, CustomClass path, boolean status) {
        Bitmap selectedBitmap = null;
        if (status) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path.getStringName(), options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateSampleSize(options);
            selectedBitmap = BitmapFactory.decodeFile(path.getStringName(), options);
        } else if (!status) {
            ContentResolver cr = activity.getContentResolver();
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(cr.openInputStream(path.getUriName()), new Rect(), options);
                options.inJustDecodeBounds = false;
                options.inSampleSize = calculateSampleSize(options);
                selectedBitmap = BitmapFactory.decodeStream(cr.openInputStream(path.getUriName()), new Rect(), options);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return selectedBitmap;
    }

    /**
     * 根据路径获得图片信息并按比例压缩，返回bitmap
     */
    private static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * @param filePath
     * @param maxLenDp 长宽中较小的度量， 最大不能超过的dp值
     * @return
     */
    public static Bitmap compressBitmap(String filePath, int maxLenDp) {
        // 设置参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
        BitmapFactory.decodeFile(filePath, options);
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 2; // 默认像素压缩比例，压缩为原图的1/2
        int minLen = Math.min(height, width); // 原图的最小边长
        if (minLen > maxLenDp) { // 如果原始图像的最小边长大于100dp（此处单位我认为是dp，而非px）
            float ratio = (float) minLen / maxLenDp; // 计算像素压缩比例
            inSampleSize = (int) ratio;
        }
        options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
        options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
        Bitmap bm = BitmapFactory.decodeFile(filePath, options); // 解码文件
        return bm;
    }

    /**
     * 设置图片缩放比例
     *
     * @param options
     * @return
     */
    private static int calculateSampleSize(BitmapFactory.Options options) {
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        int sampleSize = 1;
        int destHeight = 1000;
        int destWidth = 1000;
        if (outHeight > destHeight || outWidth > destHeight) {
            if (outHeight > outWidth) {
                sampleSize = outHeight / destHeight;
            } else {
                sampleSize = outWidth / destWidth;
            }
        }
        if (sampleSize < 1) {
            sampleSize = 1;
        }
        return sampleSize;
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param saveFile
     */
    public static void saveImage(Bitmap bitmap, File saveFile) {
        try {
            FileOutputStream fos = new FileOutputStream(saveFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 合并两图片
     *
     * @param background 背景图
     * @param foreground 前景图
     * @return
     */
    public static Bitmap combineBitmap(Bitmap background, Bitmap foreground, int startLeft, int startTop) {
        Bitmap newmap = Bitmap.createBitmap(background.getWidth(), background.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);

        Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Rect srcRect = new Rect();
        RectF dstRectF = new RectF();

        int bWidth = background.getWidth();
        int bHeight = background.getHeight();
        srcRect.set(0, 0, bWidth, bHeight);
        dstRectF.set(0f, 0f, bWidth, bHeight);
        canvas.drawBitmap(background, srcRect, dstRectF, mPaint);

        int fWidth = foreground.getWidth();
        int fHeight = foreground.getHeight();
        srcRect.set(0, 0, fWidth, fHeight);
        dstRectF.set(startLeft, startTop, startLeft + fWidth, startTop + fHeight);
        canvas.drawBitmap(foreground, srcRect, dstRectF, mPaint);//设置二维码所在的位置 这个可以写死
        canvas.save();
        canvas.restore();
        return newmap;
    }

    /**
     * 合并图片和文字
     *
     * @param background
     * @param tv
     * @param x
     * @param y
     * @return
     */
    public static Bitmap combineBitmapText(Bitmap background, TextView tv, int x, int y) {
        Bitmap newmap = Bitmap.createBitmap(background.getWidth(), background.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);

        Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Rect srcRect = new Rect();
        RectF dstRectF = new RectF();

        int bWidth = background.getWidth();
        int bHeight = background.getHeight();
        srcRect.set(0, 0, bWidth, bHeight);
        dstRectF.set(0f, 0f, bWidth, bHeight);
        canvas.drawBitmap(background, srcRect, dstRectF, mPaint);

        TextPaint textPaint = new TextPaint();
        textPaint.setColor(tv.getTextColors().getDefaultColor());
        textPaint.setTextSize(28);
        textPaint.setAntiAlias(true);

        StaticLayout layout = new StaticLayout(tv.getText().toString(), textPaint, tv.getWidth(), Layout.Alignment.ALIGN_CENTER, 1.2F, 0.0F, true);
        canvas.translate(x, y);
        layout.draw(canvas);
        canvas.save();
        canvas.restore();
        return newmap;
    }

    /**
     * Drawable 转 Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    /**
     * 重新设置Bitmap 尺寸
     *
     * @param bm
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap resetBitmapSize(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    }

    /**
     * 主体功能：照片路径实体类
     */
    public static class CustomClass implements Serializable {
        private boolean isTakePhoto;
        private String stringName;
        private Uri uriName;

        public String getStringName() {
            return stringName;
        }

        public CustomClass setStringName(String stringName) {
            this.stringName = stringName;
            return this;
        }

        public Uri getUriName() {
            return uriName;
        }

        public CustomClass setUriName(Uri uriName) {
            this.uriName = uriName;
            return this;
        }

        public boolean isTakePhoto() {
            return isTakePhoto;
        }

        public CustomClass setTakePhoto(boolean takePhoto) {
            isTakePhoto = takePhoto;
            return this;
        }
    }
}
